﻿using BasicModuleOrm.Db_Context;
using Microsoft.EntityFrameworkCore;

namespace BasicModuleOrm.ProductRespository.Respository
{
    public class EfCoreRespository<T> : IRespository<T>, ISinglaton where T : class
    {
        private EfCoreContext _efCoreContext;
        private DbSet<T> _dbSet;

        public EfCoreRespository(EfCoreContext efCoreContext)
        {
            _efCoreContext = efCoreContext;
            _dbSet = _efCoreContext.Set<T>();
        }

        public T Add(T t)
        {
            // 1、添加商品
            _dbSet.Add(t);
            _efCoreContext.SaveChanges();
            return t;
        }

        public void Delete(int id)
        {
            var t = _dbSet.Find(id);

            // 1、开始删除
            _dbSet.Remove(t);
            _efCoreContext.SaveChanges();
        }

        public IEnumerable<T> GetAll()
        {
            return _dbSet.ToList();
        }

        public T Get(int id)
        {
            // 1、查询商品
            var t = _dbSet.Find(id);

            return t;
        }

        public void Update(int id, T t)
        {
            //1、设置更新状态
            _dbSet.Update(t);

            try
            {
                //2、开始更新
                _efCoreContext.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                throw;
            }

        }
    }
}
